package utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.HashSet;

public class Test {
	private HashMap<String, Long> authorMap = new HashMap<String, Long>();
	
	public Test() throws Exception{
		initAuthorMap();
	}
	
	private void initAuthorMap() throws Exception {
		String path = "D:\\CityU\\project\\bibsonomy\\data" + "\\authorMap.txt";
		BufferedReader reader = new BufferedReader(new FileReader(path));
		String line = null;
		while ((line = reader.readLine()) != null) {
			line = line.trim();
			// System.out.println(line);
			String[] tokens = line.split("\t");
			String author = tokens[0];
			String id = tokens[1];
			authorMap.put(author, Long.valueOf(id));
		}
	}
	
	public void test(String str) throws Exception{
		
		HashSet<Long> set = extractAuthor(str);
		for(long a : set) {
			System.out.println(a);
		}
		
		//Long id = authorMap.get(str);
		//System.out.println(str + "\t" + id);
	}
	
	private HashSet<Long> extractAuthor(String au) throws Exception {
		HashSet<Long> authors = new HashSet<Long>();
		
		if(au.indexOf(" and ") == -1) {
			String str = new String(au);
			str = str.trim();
			str = str.replaceAll("\t", " ");
			str = str.replaceAll("\n", " ");
			str = str.replaceAll("\r", " ");
			str = str.trim();
			
			char[] chArr = str.toCharArray();
			str = "";
			for(char ch : chArr) {
				String c = transfer(ch);						
				str += c;
			}
			
			System.out.println(str);
			Long id = authorMap.get(str);
			if (id == null)
				return null;
			// Long id = 1L;			
			authors.add(id);
			return authors;
		}

		String[] tokens = au.split(" and ");
		for (String str : tokens) {
			str = str.trim();
			str = str.replaceAll("\t", " ");
			str = str.replaceAll("\n", " ");
			str = str.replaceAll("\r", " ");
			str = str.trim();
		
			char[] chArr = str.toCharArray();
			str = "";
			for(char ch : chArr) {
				String c = transfer(ch);				
				str += c;
			}
            str = str.trim();		
            
			Long id = authorMap.get(str);
			// Long id = 1L;
			if (id == null)
				continue;
			authors.add(id);
		}

		return authors;
	}
	
	private String transfer(char ch) {

		String c = "";
		if (ch >= 65 && ch <= 90) {
			c = Character.toString(ch);
		} else if (ch >= 97 && ch <= 122) {
			c = Character.toString(ch);
		}

		else if (Character.isWhitespace(ch)) {
			c = Character.toString(ch);
		} else {
			c = "_";
		}
		return c;
	}   
	
	public static void main(String[] args) throws Exception{
		Test app = new Test();
		String str = "Tore DybÃƒÂ¥";
		app.test(str);
	}
	
}
